#include <iostream>
#include <thread>
#include <functional>
#include <chrono>

// 类A - 数据处理器
class DataProcessor {
private:
    std::function<void(int)> callback;
    std::thread workerThread;
    
public:
    void setCallback(std::function<void(int)> cb) {
        callback = cb;
    }
    
    void startWork() {
        workerThread = std::thread([this]() {
            for (int i = 1; i <= 3; ++i) {
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
                if (callback) {
                    callback(i * 10);  // 触发回调
                }
            }
        });
    }
    
    void waitForCompletion() {
        if (workerThread.joinable()) {
            workerThread.join();
        }
    }
};

// 类B - 数据接收器
class DataReceiver {
private:
    std::string name;
    
public:
    DataReceiver(const std::string& n) : name(n) {}
    
    // 这个方法将作为回调函数
    void onDataReceived(int data) {
        // 这里的 this 指向 DataReceiver 实例
        std::cout << name << " received: " << data 
                  << " on thread: " << std::this_thread::get_id() << std::endl;
    }
    
    // 在 DataReceiver 类中设置回调
    void setupCallback(DataProcessor& processor) {
        // 在 DataReceiver 类中设置回调，this 指向 DataReceiver 实例
        processor.setCallback([this](int data) {
            this->onDataReceived(data);  // 这里的 this 是 DataReceiver*
        });
    }
};

int main() {
    DataProcessor processor;
    DataReceiver receiver("Receiver1");
    
    // 在 DataReceiver 类中设置回调
    receiver.setupCallback(processor);
    
    processor.startWork();
    processor.waitForCompletion();
    
    return 0;
}